<?php
    include("include/header.inc.php");
    include("include/func.inc.php");
    $_SESSION['page'] = 'event';
    $_SESSION['previous_page_detailTheme']= $_SERVER['REQUEST_URI'];
    $_SESSION['previous_page_register']= $_SERVER['REQUEST_URI'];
    
    echo'<div data-role="content">';
?>
<script language='JavaScript'>

    //Variable to determine if all checkboxes must be checked
    var checkflag = "false";
    
    //Function to check or uncheck all checkboxes
    function check(field) {
        if (checkflag == "false") {
            for (i = 0; i < field.length; i++) {
                if (field[i].disabled == false)
                    field[i].checked = true;
            }
            checkflag = "true";
        }
        else {
            for (i = 0; i < field.length; i++){
                field[i].checked = false;
            }
            checkflag = "false";
        }
    }
    
    //Function to ckeck prerequisite checkboxes
    function check_prerequis(field, id_theme, prerequis, postrequis){
        
        //Put prerequis in array
        var array_prerequis = prerequis.split("-");
        var array_postrequis = postrequis.split("-");
        var id_checkbox = '';
        
        for (var i=0; i<field.checkbox.length; i++){
            var id_toVerify = field.checkbox[i].id.substring(8, field.checkbox[i].id.length);
            
            if(id_toVerify == id_theme)
                id_checkbox = i;
        }
        
        if(field.checkbox[id_checkbox].checked == true){
            for (var i=0; i<array_prerequis.length; i++){
                for (var j=0; j<field.checkbox.length; j++){
                    if(field.checkbox[j].id == 'checkbox'+array_prerequis[i] && !field.checkbox[j].disabled)
                        field.checkbox[j].checked = true;
                }
            }
        }
        else{
            document.getElementById('tout').checked = false;
            if(checkflag == "false")
                checkflag = "true";
            else
                checkflag = "false";
            
            //To desactivate all prerequis checkbox
            /*
            for (var i=0; i<array_prerequis.length; i++){
                for (var j=0; j<field.checkbox.length; j++){
                    if(field.checkbox[j].id == 'checkbox'+array_prerequis[i] && !field.checkbox[j].disabled)
                        field.checkbox[j].checked = false;
                }
            }*/
        
            //To desactivate all postrequis checkbox
            for (var i=0; i<array_postrequis.length; i++){
                for (var j=0; j<field.checkbox.length; j++){
                    if(field.checkbox[j].id == 'checkbox'+array_postrequis[i] && !field.checkbox[j].disabled)
                        field.checkbox[j].checked = false;
                }
            }
        }
    }


    //To define which themes are checked to subscribe
    //Parameters: id_event is the id of the event
    //            id_theme is the last theme checked, used when there is only one theme
    function selectedThemes(id_event, id_theme){

        //Variable to stock all selected themes which will used as a parameter for the register page
        var themes = '';

        //When there is only one theme in the event
        if(document.tabForm.checkbox.length == undefined){
            //Verify that the theme were checked
            if(document.getElementById('checkbox' + id_theme).checked)
                location.href = "./register.php?event=" + id_event + "&theme=" + id_theme;
            else //Theme were not checked
                displayNoThemeSeleted();
        }
        else{ //More than one theme
            //Foreach checkboxes selected, add the theme id to the "themes" variable
            for (var i=0; i<document.tabForm.checkbox.length; i++){
                //Verify that the theme were checked
                if(document.tabForm.checkbox[i].checked){
                    themes += document.tabForm.checkbox[i].id + "-";
                    themes = themes.replace("checkbox", "");
                }
            }

            //If no theme checked
            if(themes == '')
                displayNoThemeSeleted();
            else{//One or more themes checked
                themes = themes.substr(0, themes.length-1);
                location.href = "./register.php?event=" + id_event + "&theme=" + themes;
            }
        }
    }

    //Function to display that a theme must be selected
    function displayNoThemeSeleted(){
        document.getElementById("noThemeSeleted").innerHTML = "<?php echo $texts['noThemeSelected'][$_SESSION['lang']]?>";
    }
    
</script>
<?php
   
    //Check that the "event" parameter exist in the url
    if(isset ($_GET['event'])) {
        
        //Current event id
        $id_event = $_GET['event'];
        
        //Username of the current user
        $username = strtoupper($_SESSION['login']);
        
        $rfc = connectSAP();

        //-- FUNCTION MODULE: Z_FM_M646_GET_DETAILS_EVENT --
        //We must know if the function really exists
        $fce_get_details_event = saprfc_function_discover($rfc, "Z_FM_M646_GET_DETAILS_EVENT");
        if(!$fce_get_details_event){
            echo "The function module has failed.";
            echo $rfc;
            exit;
        }
        
        //Pass import parameters
        saprfc_import ($fce_get_details_event,"IV_EVENT",$id_event);

        //Pass table parameters
        saprfc_table_init ($fce_get_details_event,"TAB_DETAILS_EVENT");

        //Call and execute the function
        $rc_get_details_event = saprfc_call_and_receive ($fce_get_details_event);            
        if ($rc_get_details_event != SAPRFC_OK){
            if ($rfc == SAPRFC_EXCEPTION )
                echo ("Exception raised: ".saprfc_exception($fce_get_details_event));
            else
                echo ("Call error: ".saprfc_error($fce_get_details_event));
            exit;
        }

        //Fetch the data from the internal tables
        $data_row = saprfc_table_rows ($fce_get_details_event,"TAB_DETAILS_EVENT");
        
        if ($data_row > 0){//If the event exist
            $DATARow = saprfc_table_read ($fce_get_details_event,"TAB_DETAILS_EVENT",1);
            
            //Define the current theme id diplayed in the list
            $id_theme;
            
            //Array to stock the current status of all themes
            $array_themes_status = array();
            
            //Variables to display the date in a correct format
            $registerDateStart = substr($DATARow['STARTREG'],-2).'.'.substr($DATARow['STARTREG'],4,2).'.'.substr($DATARow['STARTREG'],0,4);
            $registerDateEnd = substr($DATARow['ENDREG'],-2).'.'.substr($DATARow['ENDREG'],4,2).'.'.substr($DATARow['ENDREG'],0,4);
            
            //To compare the registration dates with the current date
            $today = date('d.m.Y');
            $todayFormat = explode(".", $today); 
            $dateToday = $todayFormat[2].$todayFormat[1].$todayFormat[0];

            $registerStart = explode(".", $registerDateStart);
            $dateRegisterStart = $registerStart[2].$registerStart[1].$registerStart[0];

            $registerEnd = explode(".", $registerDateEnd);
            $dateRegisterEnd = $registerEnd[2].$registerEnd[1].$registerEnd[0];
            
            if (($dateToday >=$dateRegisterStart)&&($dateToday<=$dateRegisterEnd))
                $registration = 'OK';
            else
                $registration = 'KO';
            //Display information about the event
            //Title
            echo '<h2>' . htmlentities($DATARow['TITLE']) . '</h2>';
            echo '<div class="tableauPage">';
                echo'<form id="tabForm" name="tabForm">';
                //Description
                echo '<p><b>' . $texts['description'][$_SESSION['lang']] . '</b> : '.htmlentities($DATARow['DESCRIPTION']).'</p>';
                //Site
                if($DATARow['WEBSITE'] <> '')
                    echo '<p><b>' . $texts['website'][$_SESSION['lang']] . '</b> : <a href="http://'.$DATARow['WEBSITE'].'" target="_blank">'.htmlentities($DATARow['WEBSITE']).'</a></p>';
                
                //Email
                if($DATARow['EMAIL'] <> '')
                    echo '<p><b>' . $texts['contact'][$_SESSION['lang']] . '</b> : '.htmlentities($DATARow['EMAIL']).'</p>';
                //Dates of registration
                echo '<p><b>' . $texts['registration'][$_SESSION['lang']] . '</b> : ' . $texts['from'][$_SESSION['lang']] . ' ' . $registerDateStart.' ' . $texts['to'][$_SESSION['lang']] . ' '.$registerDateEnd.'</p>';
                //Table with all themes
                echo '<table width="100%" cellspacing="0"><tr class="titreTableau">';
                    //Title of the table
                    echo '<td>' . $texts['theme'][$_SESSION['lang']] . '</td>';
                    echo '<td>' . $texts['date'][$_SESSION['lang']] . '</td>';
                    echo '<td align="center">' . $texts['availability'][$_SESSION['lang']] . '*</td>';
                    //Checkbox column
                    echo '<td align="center"><input name="tout" id="tout" type="checkbox" ';
                    //To disable if today date is not between the registation dates
                    if($dateToday < $dateRegisterStart || $dateToday > $dateRegisterEnd)
                        echo 'DISABLED ';
                    echo 'onClick="this.value=check(this.form);"/></td>';
                echo '<tr>';

                //Details foreach themes if there is/are
                for ($i=1; $i<=$data_row; $i++){
                    $DATARow = saprfc_table_read ($fce_get_details_event,"TAB_DETAILS_EVENT",$i);
                    //Set id of the currernt theme
                    $id_theme = $DATARow['THEME_ID'];
                    
                    //Variables to display the date in a correct format 
                    $dateStart = substr($DATARow['STARTDATE'],-2).'.'.substr($DATARow['STARTDATE'],4,2).'.'.substr($DATARow['STARTDATE'],0,4);
                    $dateEnd = substr($DATARow['ENDDATE'],-2).'.'.substr($DATARow['ENDDATE'],4,2).'.'.substr($DATARow['ENDDATE'],0,4); 

                    //-- FUNCTION MODULE: Z_FM_M646_GET_PARTICIPANTS --
                    //Test how many people are subscribed to display the disponibility
                    
                    //We must know if the function really exists
                    $fce_get_participants = saprfc_function_discover($rfc, "Z_FM_M646_GET_PARTICIPANTS");
                    if(!$fce_get_participants){
                        echo "The function module has failed.";
                        echo $rfc;
                        exit;
                    }    

                    //Pass import parameters
                    saprfc_import ($fce_get_participants,"IV_THEME",$DATARow['THEME_ID']);

                    //Pass table parameters
                    saprfc_table_init ($fce_get_participants,"TAB_MEMBERS");

                    //Call and execute the function
                    $rc_get_participants = saprfc_call_and_receive ($fce_get_participants);            
                    if ($rc_get_participants != SAPRFC_OK){
                        if ($rfc == SAPRFC_EXCEPTION )
                            echo ("Exception raised: ".saprfc_exception($fce_get_participants));
                        else
                            echo ("Call error: ".saprfc_error($fce_get_participants));
                        exit;
                    }

                    //Fetch the data from the internal tables
                    $nb_registration = saprfc_table_rows ($fce_get_participants,"TAB_MEMBERS");
                    //realease the function 
                    saprfc_function_free($fce_get_participants);
                    
                    //-- FUNCTION MODULE: Z_FM_M646_GET_REGISTRATION --
                    //Test if the user is already registered
                    //To know if the checkbox must be active

                    //We must know if the function really exists
                    $fce_get_registration = saprfc_function_discover($rfc, "Z_FM_M646_GET_REGISTRATION");
                    if(!$fce_get_registration){
                        echo "The function module has failed.";
                        echo $rfc;
                        exit;
                    }

                    //Pass import parameters
                    saprfc_import ($fce_get_registration,"IV_THEME", $id_theme);
                    saprfc_import ($fce_get_registration,"IV_MEMBER", $username);

                    //Pass table parameters
                    saprfc_table_init ($fce_get_registration, "TAB_REGISTRATION");

                    //Call and execute the function
                    $rc_get_registration = saprfc_call_and_receive ($fce_get_registration);            
                    if ($rc_get_registration != SAPRFC_OK){
                        if ($rfc == SAPRFC_EXCEPTION )
                            echo ("Exception raised: ".saprfc_exception($fce_get_registration));
                        else
                            echo ("Call error: ".saprfc_error($fce_get_registration));
                        exit;
                    }

                    //Fetch the data from the internal tables
                    $data_rowRegistration = saprfc_table_rows ($fce_get_registration,"TAB_REGISTRATION");

                    //Variable to define the status of the registration
                    $alreadyRegistered;
                    //Variable can have the following status :
                    //'n' = no registration
                    //'r' = registered
                    //'c' = cancelled
                    //'w' = waiting

                    //Id of the current registration (only if it exist)
                    $id_registration;

                    if ($data_rowRegistration > 0){//If the registration exist   
                        $DATARowRegistration = saprfc_table_read ($fce_get_registration,"TAB_REGISTRATION",1);
                        //Set the status and id
                        $alreadyRegistered = $DATARowRegistration['STATUS'];
                        $id_registration = $DATARowRegistration['ID'];
                    }
                    else //No registration
                        $alreadyRegistered = 'n';

                    //realease the function
                    saprfc_function_free($fce_get_registration);
                    
                    //Set current status of current theme
                    $array_themes_status[$i-1][0] = $id_theme;
                    $array_themes_status[$i-1][1] = $alreadyRegistered;                    
                    
                    
                    //Keep all prerequis foreach themes
                    //-- FUNCTION MODULE: Z_FM_M646_THEME_PREREQUIS --
                    //We must know if the function really exists
                    $fce_theme_prerequis = saprfc_function_discover($rfc, "Z_FM_M646_THEME_PREREQUIS");
                    if(!$fce_theme_prerequis){
                        echo "The function module has failed.";
                        echo $rfc;
                        exit;
                    }
                    
                    //Pass import parameters
                    saprfc_import ($fce_theme_prerequis,"IP_THEMEID",$id_theme);

                    //Pass table parameters
                    saprfc_table_init ($fce_theme_prerequis,"TAB_PREREQUIS");

                    //Call and execute the function
                    $rc_theme_prerequis = saprfc_call_and_receive ($fce_theme_prerequis);            
                    if ($rc_theme_prerequis != SAPRFC_OK){
                        if ($rfc == SAPRFC_EXCEPTION )
                            echo ("Exception raised: ".saprfc_exception($fce_theme_prerequis));
                        else
                            echo ("Call error: ".saprfc_error($fce_theme_prerequis));
                        exit;
                    }

                    //Fetch the data from the internal tables
                    $data_row_theme_prerequis = saprfc_table_rows ($fce_theme_prerequis,"TAB_PREREQUIS");
                    
                    if ($data_row_theme_prerequis > 0){//If there is/are prerequisites
                        
                        //Foreach prerequisites
                        for ($j=1; $j<=$data_row_theme_prerequis; $j++){
                            $DATARow_theme_prerequis = saprfc_table_read ($fce_theme_prerequis,"TAB_PREREQUIS",$j);

                            $current_prerequis = $DATARow_theme_prerequis['THEME_ID'];
                            $array_themes_status[$i-1][2].= $current_prerequis.'-';
                        }
                    }
                    
                    //realease the function
                    saprfc_function_free($fce_theme_prerequis);
                    
                    if (strpos($array_themes_status[$i-1][2],'-')==true)
                        $array_themes_status[$i-1][2] = substr($array_themes_status[$i-1][2], 0, strlen($array_themes_status[$i-1][2])-1);
                    
                    //Get postrequis to have it for checkboxes
                    
                    //-- FUNCTION MODULE: Z_FM_M646_THEME_POSTREQUIS --
                    //We must know if the function really exists
                    $fce_theme_postrequis = saprfc_function_discover($rfc, "Z_FM_M646_THEME_POSTREQUIS");
                    if(!$fce_theme_postrequis){
                        echo "The function module has failed.";
                        echo $rfc;
                        exit;
                    }

                    //Pass import parameters
                    saprfc_import ($fce_theme_postrequis,"IV_THEMEID",$id_theme);

                    //Pass table parameters
                    saprfc_table_init ($fce_theme_postrequis,"TAB_POSTREQUIS");

                    //Call and execute the function
                    $rc_theme_postrequis = saprfc_call_and_receive ($fce_theme_postrequis);            
                    if ($rc_theme_postrequis != SAPRFC_OK){
                        if ($rfc == SAPRFC_EXCEPTION )
                            echo ("Exception raised: ".saprfc_exception($fce_theme_postrequis));
                        else
                            echo ("Call error: ".saprfc_error($fce_theme_postrequis));
                        exit;
                    }

                    //Fetch the data from the internal tables
                    $data_row_theme_postrequis = saprfc_table_rows ($fce_theme_postrequis,"TAB_POSTREQUIS");

                    if ($data_row_theme_postrequis > 0){//If there is/are postrequisites

                        //Foreach postrequisites
                        for ($y=1; $y<=$data_row_theme_postrequis; $y++){
                            $DATARow_theme_postrequis = saprfc_table_read ($fce_theme_postrequis,"TAB_POSTREQUIS",$y);

                            $current_postrequis = $DATARow_theme_postrequis['THEME_ID'];
                            $array_themes_status[$i-1][3].= $current_postrequis.'-';
                        }
                    }
                    //realease the function
                    saprfc_function_free($fce_theme_postrequis); 

                    if (strpos($array_themes_status[$i-1][3],'-')==true)
                        $array_themes_status[$i-1][3] = substr($array_themes_status[$i-1][3], 0, strlen($array_themes_status[$i-1][3])-1);
        
                    //To display 2 different color in the table (even and odd lignes)
                    $rem = $i % 2;
                    if($rem == 0)
                        echo "<tr bgcolor='#D3D3D3'>";
                    else
                        echo "<tr bgcolor='#FFFFFF'>";
                    //Title of theme
                    echo '<td><a href="./detailTheme.php?theme='.$DATARow['THEME_ID'].'&event='.$id_event.'"><img height="17px" src="picture/lens.png"/> '.htmlentities($DATARow['THEME_TITLE']).'</a></td>';
                    //Display dates (one or more days)
                    if($dateStart == $dateEnd)
                        echo '<td>'.$dateStart.'</td>';
                    else
                        echo '<td>'. $texts['from'][$_SESSION['lang']] .' '.$dateStart.' '. $texts['to'][$_SESSION['lang']] .' '.$dateEnd.'</td>';
                    
                    //Display disponibilities and checkbox
                    // If the user is already registered on the waiting list
                    if($alreadyRegistered == 'r' || $alreadyRegistered == 'w'){
                        // Grey icon
                        echo "<td align=\"center\"><img src='./picture/grey.gif'/></td>";
                        // Disable checkbox
                        echo "<td align=\"center\"><input type=\"checkbox\" DISABLED id=\"checkbox".$DATARow['THEME_ID']."\" name=\"checkbox\"/></td>";    
                    } 
                    // Not registered yet
                    else {
                        //Test if the subscription is open with the dates                 
                        if($dateToday > $dateRegisterEnd){//Closed
                            echo "<td align=\"center\"><img src='./picture/red.gif'/></td>";
                            echo "<td align=\"center\"><input type=\"checkbox\" DISABLED id=\"checkbox".$DATARow['THEME_ID']."\" name=\"checkbox\"/></td>";
                        }
                        else {//Open
                            //Test the number of subscriptions
                            if ($nb_registration < $DATARow['MAXPEOPLE'])//Available
                                echo "<td align=\"center\"><img src='./picture/green.gif'/></td>";
                            else//Complete
                                echo "<td align=\"center\"><img src='./picture/orange.gif'/></td>";

                            if ($registration == 'OK')
                                echo "<td align=\"center\"><input type=\"checkbox\" id=\"checkbox".$DATARow['THEME_ID']."\" name=\"checkbox\" OnClick=\"check_prerequis(this.form, ".$DATARow['THEME_ID'].", '".$array_themes_status[$i-1][2]."', '".$array_themes_status[$i-1][3]."')\";/></td>";
                            else                            
                                echo "<td align=\"center\"><input type=\"checkbox\" DISABLED id=\"checkbox".$DATARow['THEME_ID']."\" name=\"checkbox\"/></td>";    
                            }                    
                    }
                    echo "</tr>";
                }
                
                $_SESSION['array_themes_status'] = array();
                $_SESSION['array_themes_status']= $array_themes_status;
                   
                echo "</table>";
                //Description of disponibilites icons
                echo "<br/>*<img src='./picture/red.gif'/> = " . $texts['past'][$_SESSION['lang']] . ", <img src='./picture/orange.gif'/> =  " . $texts['complete'][$_SESSION['lang']] . ", <img src='./picture/green.gif'/> = " . $texts['open'][$_SESSION['lang']] . ", <img src='./picture/grey.gif'/> = " . $texts['registered'][$_SESSION['lang']];// . ", <img src='./picture/blue.gif'/> = " . $texts['already_time'][$_SESSION['lang']] . "";
                echo'</form>';
                
                //Paragaphe will be display if no theme selected when subscription button clicked    
                echo'<p id="noThemeSeleted" align="center" style="color:red; font-weight:bold;"></p>';
                //Subscription button
                if ($registration == 'OK')
                    echo'<p align="center"><input type="button" value="' . $texts['register'][$_SESSION['lang']] . '" data-inline="true" onClick="selectedThemes('.$id_event.','.$id_theme.')" /></p>';
                if ($_SESSION['name'] <> '')//Verify if the user is a guest, he can't go back
                    echo'<p align="center"><a href="./events.php" rel="external" data-role="button" data-inline="true">'.$texts['back'][$_SESSION['lang']].'</a></p>';
            echo'</div>';  
        }
        else{//These event does not exist
            echo '<h2>'.$texts['error'][$_SESSION['lang']].'</h2>';
            echo '<div class="tableauPage">';
                echo '<p align="center">'.$texts['event_not_found'][$_SESSION['lang']].'<br/><br/>';
                echo '<a href="./events.php" rel="external" data-role="button" data-inline="true">'.$texts['back'][$_SESSION['lang']].'</a>';
            echo '</p></div>';
        }
        
        //Realease the function and close the connection
        saprfc_function_free($fce_get_details_event);
        saprfc_close($rfc);      
    }
    else{//The parameter "event" does not exist in the url
        echo '<h2>'.$texts['error'][$_SESSION['lang']].'</h2>';
        echo '<div class="tableauPage">';
            echo '<p align="center">'.$texts['event_not_found'][$_SESSION['lang']].'<br/><br/>';
            echo '<a href="./events.php" rel="external" data-role="button" data-inline="true">'.$texts['back'][$_SESSION['lang']].'</a>';
        echo '</p></div>';
    }
    echo '</div>';
    include('include/footer.inc.php');  // Call footer
    ?>